//
//  RegisterViewController.m
//  eGifr
//
//  Created by Phien Tram on 8/4/13.
//  Copyright (c) 2013 eGiftr. All rights reserved.
//

#import "RegisterViewController.h"
#import "UserDefaultHelper.h"
#import <CoreLocation/CoreLocation.h>
#import "ServiceNameMapper.h"
#import "NSDictionary+Utility.h"

@interface RegisterViewController ()

@property (nonatomic, strong) NSString *city;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;

@end

@implementation RegisterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - IBAction methods

- (IBAction)registerButtonOnClicked:(id)sender
{
    [_spinner startAnimating];
    NSString *message = @"";
    if (_nameTextField.text.length == 0) {
        message = @"Username is invalid";
    } else if (_emailTextField.text.length == 0) {
        message = @"Email address is invalid";
    } else if (_passwordTextField.text.length == 0) {
        message = @"Password is invalid";
    } else if (_cityTextField.text.length == 0) {
        message = @"City is invalid";
    }
    
    if (message.length > 0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry" message:message delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        [alertView show];
    } else {
        
        
        CLGeocoder *gc = [[CLGeocoder alloc] init];
        [gc geocodeAddressString:_cityTextField.text completionHandler:^(NSArray *placemarks, NSError *error)
        {
            if ([placemarks count]>0)
            {
                // get the first one
                CLPlacemark* mark = (CLPlacemark *)[placemarks objectAtIndex:0];
                _coordinate = mark.location.coordinate;
                NSLog(@"lat:%f lng:%f", _coordinate.latitude, _coordinate.longitude);
                self.city = [mark locality];
                
                self.dataManager = [DataManager userRegister:self userName:_nameTextField.text email:_emailTextField.text password:_passwordTextField.text city:_cityTextField.text fbId:@"" fbToken:@"" isFbUser:NO];
            }
            else
            {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"Current city was not located! Please try again!" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
                [alertView show];
            }
        }];
    }
    
}

#pragma mark - UITextField delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return NO;
}

#pragma mark - Private methods

- (void)onSuccessfulRegistration
{
    [_spinner stopAnimating];
    [_delegate registerViewSuccessful:self];
}

#pragma mark - DataManager delegate

- (void)dataManagerFinishGetData:(DataManager *)dataManager response:(id)response error:(NSError *)error
{
    [_spinner stopAnimating];
    
    if (error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry" message:error.localizedDescription delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        [alertView show];
    } else {
        if ([dataManager.serviceName isEqualToString:[ServiceNameMapper userRegister]]) {
            //Success
            NSLog(@"%@", response);
            if (response) {
                NSString *userId = [response objectOrNilForKey:@"userId"];
                [UserDefaultHelper setUserId:userId];
            }
            
            [UserDefaultHelper setUsername:_nameTextField.text];
            [UserDefaultHelper setEmailAddress:_emailTextField.text];
            [UserDefaultHelper setPassword:_passwordTextField.text];
            [UserDefaultHelper setCity:_city];
            [UserDefaultHelper setLatitude:_coordinate.latitude];
            [UserDefaultHelper setLongitude:_coordinate.longitude];
            
            [_delegate registerViewSuccessful:self];
        }
    }
}

@end
